<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库时间" prop="startdate">
        <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.beginCreatedate" type="date"
                        value-format="yyyy-MM-dd" placeholder="选择开始日期"
        >
        </el-date-picker>
        <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.endCreatedate" type="date"
                        value-format="yyyy-MM-dd" placeholder="选择结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="公司" prop="orgguid">
        <el-select v-model="queryParams.orgguid" placeholder="请选择公司" filterable clearable>
          <el-option
            v-for="item in orgOptions"
            :key="item.guid"
            :label="item.name"
            :value="item.guid"
            @click.native="getStore($event, item)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="库房" prop="storermguid">
        <el-select v-model="queryParams.storermguid" placeholder="请选择库房" filterable clearable>
          <el-option
            v-for="item in roomOptions"
            :key="item.guid"
            :label="item.name"
            :value="item.guid"
            @click.native="getRoom($event, item)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="库间" prop="shrguid">
        <el-select v-model="queryParams.shrguid" placeholder="请选择库间" filterable clearable>
          <el-option
            v-for="item in storeroomhousrOptions"
            :key="item.guid"
            :label="item.name"
            :value="item.guid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品" prop="productid">
        <el-select v-model="queryParams.productid" placeholder="请选择产品" filterable clearable>
          <el-option
            v-for="item in productOptions"
            :key="item.guid"
            :label="item.productname"
            :value="item.guid"
            @click.native="getSp($event, item)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物料" prop="spid">
        <el-select v-model="queryParams.spid" placeholder="请选择物料" filterable clearable>
          <el-option
            v-for="item in specificationOptions"
            :key="item.guid"
            :label="item.name"
            :value="item.guid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="入库类型" prop="whintype">
        <el-select v-model="queryParams.whintype" placeholder="请选择入库类型" filterable clearable>
          <el-option
            v-for="item in whintypeOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="queryParams.supplierId" placeholder="请选择客户" filterable clearable>
          <el-option
            v-for="item in supplierOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单编号" prop="businesscode">
        <el-input
          v-model="queryParams.businesscode"
          placeholder="请输入订单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库单编号" prop="formno" label-width="100px">
        <el-input
          v-model="queryParams.formno"
          placeholder="请输入入库单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bill:whinform:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-download"
          size="mini"
          :disabled="single"
          @click="handlePrint"
        >打印入库单
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="whinformList" border :span-method="objectSpanMethod"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="入库单编号" align="center" prop="formno"/>
      <el-table-column label="订单编号" align="center" prop="businesscode"/>
      <el-table-column label="入库日期" align="center" prop="createdate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入库类型" align="center" prop="whintype" :formatter="whintypeFormat"/>
      <el-table-column label="库存组织" align="center" prop="orgname"/>
      <el-table-column label="库房" align="center" prop="srname"/>
      <el-table-column label="库间" align="center" prop="shname"/>
      <el-table-column label="产品" align="center" prop="productname"/>
      <el-table-column label="规格" align="center" prop="spename" width="130"/>
      <el-table-column label="重量" align="center" prop="weight"/>
      <el-table-column label="单位" align="center" prop="stockunit"/>
      <el-table-column label="结算组织" align="center" prop="settlOrgName"/>
      <el-table-column label="供应商" align="center" prop="supplierName" width="130"/>
      <el-table-column label="操作人" align="center" prop="operator"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 打印入库单对话框 -->
    <el-dialog :visible.sync="open" width="1010px" append-to-body>
      <div id="printContent">
        <div class="brand-article" v-html="this.msgInfo"></div>
      </div>
      <span slot="footer" class="dialog-footer">
            <el-button type="warning" icon="el-icon-download" size="mini" @click="exportData">导出</el-button>
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" v-print="print">打印</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWhinform,
  getWhinform,
  delWhinform,
  addWhinform,
  updateWhinform,
  exportWhinform,
  whinPrintHtml,
  whinExportHtml
} from '@/api/bill/whinform'
import Print from 'vue-print-nb'
import Vue from 'vue'
import {getMergedData} from '@/utils/mergedArray'
Vue.use(Print)
import {
  findStoreroomListByPermiss,
  findStorehouse,
  findOrganizationList,
  findSupploerlist,
  findProductList,
  findSpecificationList
} from '@/api/public'

export default {
  name: 'Whinform',
  components: {},
  data() {
    return {
      print: {
        id: 'printContent',
        popTitle: '&nbsp', // 打印配置页上方的标题
        extraHead: '', // 左上方的头部文字，附加在head标签上的额外标签，使用逗号分割
        preview: false, // 是否启动预览模式，默认是false
        previewTitle: '预览的标题', // 打印预览的标题
        previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
        zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
        previewBeforeOpenCallback() {
          console.log('正在加载预览窗口！')
        }, // 预览窗口打开之前的callback
        previewOpenCallback() {
          console.log('已经加载完预览窗口，预览打开了！')
        }, // 预览窗口打开时的callback
        beforeOpenCallback() {
          console.log('开始打印之前！')
        }, // 开始打印之前的callback
        openCallback() {
          console.log('执行打印了！')
        }, // 调用打印时的callback
        closeCallback() {
          console.log('关闭了打印工具！')
        }, // 关闭打印的callback(无法区分确认or取消)
        clickMounted() {
          console.log('点击v-print绑定的按钮了！')
        },
        // url: 'http://localhost:8080/', // 打印指定的URL，确保同源策略相同
        // asyncUrl (reslove) {
        //   setTimeout(() => {
        //     reslove('http://localhost:8080/')
        //   }, 2000)
        // },
        standard: '',
        extarCss: ''
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库单表格数据
      whinformList: [],
      //打印入库单html数据
      msgInfo: {},
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 入库类型字典
      whintypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        beginCreatedate: this.getMonthFirDate(),
        endCreatedate: null,
        storermguid: null,
        shrguid: null,
        whintype: null,
        orgguid: null,
        supplierId: null,
        businesscode: null,
        formno: null,
        spid: null,
        productid: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        guid: [
          { required: true, message: '主键不能为空', trigger: 'blur' }
        ],
        formno: [
          { required: true, message: '编号不能为空', trigger: 'blur' }
        ],
        storermguid: [
          { required: true, message: '库房id不能为空', trigger: 'blur' }
        ],
        lastupdate: [
          { required: true, message: '最后修改时间不能为空', trigger: 'blur' }
        ]
      },
      roomOptions: [],
      storeroomhousrOptions: [],
      outtypeOptions: [],
      orgOptions: [],
      supplierOptions: [],
      rowIndex: '-1',
      OrderIndexArr: [],
      hoverOrderArr: [],
      productOptions: [],
      specificationOptions: [],
      // mergedColumns: [],
      //表单合并单元格数据
      formMergedArray: []
    }
  },
  created() {
    this.getList()

    this.findSupploerlist()
    this.findOrganizationList()
    this.findProductList()
    this.getDicts('in_form_type').then(response => {
      this.whintypeOptions = response.data
    })
  },
  methods: {
    exportData() {
      let that = this
      let data = {
        autoid: that.ids[0]
      }
      that.$confirm('是否确认导出入库单数据？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(function() {
        return whinExportHtml(data).then(response => {
          that.download(response.msg)
        })
      })
    },
    /** 打印出库单按钮操作 */
    handlePrint() {
      this.open = true
      let data = {
        autoid: this.ids[0]
      }
      this.msgInfo={};
      whinPrintHtml(data).then(response => {
        this.msgInfo = response.msg
        console.log('this.msgInfo:---------------')
        console.log(this.msgInfo)
      })
    },
    findProductList() {
      findProductList().then(response => {
        this.productOptions = response.data
      })
    },
    //客户
    findSupploerlist() {
      findSupploerlist().then(response => {
        this.supplierOptions = response.data
      })
    },
    //组织
    findOrganizationList() {
      findOrganizationList().then(response => {
        this.orgOptions = response.data
      })
    },
    getSp(event, item) {
      findSpecificationList({ productguid: item.guid }).then(response => {
        this.specificationOptions = response.data
      })
    },
    getStore(event, item) {
      findStoreroomListByPermiss({ orgguid: item.guid, functionType: 10 }).then(response => {
        this.roomOptions = response.data
      })
    },
    //库间
    getRoom(event, item) {
      findStorehouse({ storeguid: item.guid }).then(response => {
        this.storeroomhousrOptions = response.data
      })
    },
    /** 查询入库单列表 */
    getList() {
      this.loading = true
      listWhinform(this.queryParams).then(response => {
        this.whinformList = response.rows
        this.total = response.total
        this.loading = false
        // this.gatherTableData()
        this.transferData()
      })
    },
    // 入库类型字典翻译
    whintypeFormat(row, column) {
      return this.selectDictLabel(this.whintypeOptions, row.whintype)
    },

    //转换数据，测试
    transferData() {
      let data = []
      this.whinformList.forEach((element, index) => {
        let rows = []
        rows.push(element.autoid)
        rows.push(element.formno)
        rows.push(element.businesscode)
        rows.push(element.createdate)
        rows.push(element.whintype)
        rows.push(element.orgname)
        rows.push(element.srname)
        rows.push(element.shname)
        rows.push(element.productname)
        rows.push(element.spename)
        rows.push(element.weight)
        rows.push(element.stockunit)
        rows.push(element.settlOrgName)
        rows.push(element.supplierName)
        rows.push(element.operator)
        data.push(rows)
      })
      let colIndexs = [0, 1, 2, 3, 4, 5,12,13,14 ];
      this.formMergedArray=[];
      getMergedData(data, 0,colIndexs,this.formMergedArray)
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        autoid: null,
        guid: null,
        formno: null,
        pbguid: null,
        foguid: null,
        storermguid: null,
        storehguid: null,
        storehcode: null,
        productid: null,
        productname: null,
        qty: null,
        unit: null,
        price: null,
        puserguid: null,
        pusername: null,
        carcode: null,
        drviername: null,
        driverphone: null,
        createdate: null,
        operatorid: null,
        lastupdate: null,
        remark: null,
        whintype: null,
        orgguid: null,
        orgname: null,
        businesscode: null,
        settlOrgId: null,
        settlOrgName: null,
        supplierId: null,
        supplierName: null,
        currency: null,
        departmentid: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.autoid)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加入库单'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const autoid = row.autoid || this.ids
      getWhinform(autoid).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改入库单'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.autoid != null) {
            updateWhinform(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addWhinform(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const autoids = row.autoid || this.ids
      this.$confirm('是否确认删除该数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delWhinform(autoids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有入库单数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportWhinform(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    },

    // 获取相同编号的订单
    gatherTableData() {
      let OrderObj = {}
      this.whinformList.forEach((element, index) => {
        element.rowIndex = index
        if (OrderObj[element.formno]) {
          OrderObj[element.formno].push(index)
        } else {
          OrderObj[element.formno] = []
          OrderObj[element.formno].push(index)
        }
      })

      // 将数组长度大于1的值 存储到this.OrderIndexArr（也就是需要合并的项）
      this.OrderIndexArr = []
      for (let k in OrderObj) {
        if (OrderObj[k].length > 1) {
          this.OrderIndexArr.push(OrderObj[k])
        }
      }
    },

    // 合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      for (let i = 0; i < this.formMergedArray.length; i++) {
        let element = this.formMergedArray[i]
        if (rowIndex == element.row && columnIndex == element.col) {
          return {
            rowspan: element.span,
            colspan: 1
          }
        }else if(rowIndex>element.row && rowIndex<=(element.row+element.span-1) && columnIndex==element.col){
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },

  // 合并单元格
  objectSpanMethod1({ row, column, rowIndex, columnIndex }) {
    let colIndexs = [0, 1, 2, 3, 4, 5, 12, 13, 14]
    if (colIndexs.indexOf(columnIndex) > -1) {
      for (let i = 0; i < this.OrderIndexArr.length; i++) {
        let element = this.OrderIndexArr[i]
        for (let j = 0; j < element.length; j++) {
          let item = element[j]
          if (rowIndex == item) {
            if (j == 0) {
              return {
                rowspan: element.length,
                colspan: 1
              }
            } else if (j != 0) {
              return {
                rowspan: 0,
                colspan: 0
              }
            }
          }
        }
      }
    }
  }
}
}

</script>
